package com.njwb.day15.zqzb.jdbc02;

import java.sql.*;

public class AddStudentTest {
    public static void main(String[] args) {
        String name = "小乔";
        int age = 23 ;
        String address= "南京";
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        try {
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
            //3、准备sql
            String sql = "insert into tb_student(sname,age,address) values(?,?,?)";
            //4、创建命令器
            pstmt = connection.prepareStatement(sql);
            //5、设置参数
            pstmt.setString(1,name);
            pstmt.setInt(2,age);
            pstmt.setString(3,address);
            //6、执行sql语句 executeUpdate该方法主要用做更新操作,返回值表示受影响的行数
            int result = pstmt.executeUpdate();
            if(result>0) {
                System.out.println("数据添加成功！！！");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源 （倒着关闭）
            if(pstmt!=null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
